package com.ruyue.csinstall.command.impl;

import com.ruyue.csinstall.command.Command;
import com.ruyue.csinstall.model.CsPro;
import com.ruyue.csinstall.model.quote.AppLoader;
import com.ruyue.csinstall.model.quote.AppMetadata;
import com.ruyue.csinstall.model.quote.DefaultAppLoader;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.util.ClassUtils;
import org.springframework.util.FileCopyUtils;
import org.springframework.util.StringUtils;

import java.io.File;
import java.io.FileFilter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

/**
 * 初始化通讯机
 * @author xiawl
 * @create 2017/7/23 15:42.
 */
public class InitCommand implements Command {
    private static final Log log = LogFactory.getLog(InitCommand.class);
    private String directoryApps;
    private String directoryDeploys;
    private AppLoader appLoader = new DefaultAppLoader();

    public InitCommand(CsPro csPro) {
        this.directoryApps = String.format("%s/comm-server/apps", csPro.getUnZipPath());
        this.directoryDeploys = String.format("%s/comm-server/deploys", csPro.getUnZipPath());
    }

    @Override
    public boolean execute() {
        try {
            log.info(String.format("通讯机初始化开始[%s]...", this.directoryApps));
            List<AppMetadata> appMetadataList = scanApps();
            deployApps(appMetadataList);
            log.info("通讯机初始化结束...");
            return true;
        } catch (Exception e) {
            log.error("通讯机初始化失败,请检查应用打包格式是否正确", e);
            return false;
        }
    }

    private java.util.List<AppMetadata> scanApps() throws IOException {
        //
        File[] appFiles = new File(directoryApps).listFiles(new FileFilter() {
            public boolean accept(File pathname) {
                return pathname.getName().endsWith(".zip");
            }
        });
        File deploysDirectory = new File(directoryDeploys);
        //
        java.util.List<AppMetadata> appMetadataList = new ArrayList<AppMetadata>();
        if (appFiles != null){
            for(File appFile : appFiles) {
                appLoader.setClassLoader(ClassUtils.getDefaultClassLoader());
                AppMetadata appMetadata = null;
                appMetadata = appLoader.load(appFile,deploysDirectory);
                appMetadataList.add(appMetadata);
            }
        }
        //
        return appMetadataList;
    }

    private void deployApps(java.util.List<AppMetadata> appMetadataList) throws IOException {
        //
        for (AppMetadata appMetadata : appMetadataList) {
            //
            String appConf = appMetadata.getProperties().getProperty("app.conf", "");
            File confDirectory = new File(directoryApps, "../conf/" + appMetadata.getId());
            //
            if (StringUtils.hasText(appConf)) {
                if (appConf.contains(" ") || appConf.contains(",") || appConf.contains("|")) {
                    log.debug("app.conf 配置项格式错误，请使用正确的分隔符 ';' 对多个配置文件进行分割！");
                }
                String[] appConfFileNames = StringUtils.tokenizeToStringArray(appConf, ";");
                if (appConfFileNames == null) {
                    appConfFileNames = new String[]{appConf};
                }
                for (String appConfFileName : appConfFileNames) {
                    if (StringUtils.hasText(appConfFileName.trim()) == false) {
                        continue;
                    }
                    //
                    File inAppConfFile = new File(appMetadata.getAppDirectory(), appConfFileName);
                    File outAppConfFile = new File(confDirectory, inAppConfFile.getName());
                    if (outAppConfFile.exists() == false) {
                        if (!outAppConfFile.getParentFile().exists() && !outAppConfFile.getParentFile().mkdirs()) {
                            log.debug("创建目录失败..." + outAppConfFile.getParentFile().getAbsolutePath());
                        }
                        if (!outAppConfFile.createNewFile()) {
                            log.debug("创建文件失败..." + outAppConfFile.getAbsolutePath());
                        }
                        //
                        FileCopyUtils.copy(inAppConfFile, outAppConfFile);
                    }
                }
            }
            if (confDirectory.exists()) {
                appMetadata.getClassLoader().addClassPath(confDirectory.toURI().toURL());
            }
        }
    }

}